package log

import (
	"fmt"
	"gitee.com/xluomo945/fm/log/driver"
	"gitee.com/xluomo945/fm/setting"
	syslog "log"
	"os"
)

var logger setting.LogWriter
var c setting.LoggerConfig

var drivers = map[setting.LogDriver]func(config setting.LoggerConfig) (setting.LogWriter, error){
	setting.DB:      db,
	setting.Console: console,
	setting.File:    file,
}

func Create(config setting.LoggerConfig, isTrace bool) error {
	if logger != nil {
		return nil
	}

	handle, err := drivers[config.Type](config)
	if err != nil {
		return err
	}

	c = config

	logger = handle
	if isTrace {
		logger.OpenTrace()
	}

	syslog.Println("[INFO] logger type is", config.Type)
	return nil
}

func db(config setting.LoggerConfig) (setting.LogWriter, error) {
	return driver.DBCreate(config)
}

func console(config setting.LoggerConfig) (setting.LogWriter, error) {
	return driver.ConsoleCreate(config)
}

func file(config setting.LoggerConfig) (setting.LogWriter, error) {
	return driver.FileCreate(config)
}

func Close() {
	if logger != nil {
		logger.Close()
	}
}

func customName(date string) string {
	if !c.ByDay {
		return fmt.Sprintf("%s%s%s", c.Dir, string(os.PathSeparator), c.Name)
	}
	return fmt.Sprintf("%s%s%s_%s", c.Dir, string(os.PathSeparator), c.Name, date)
}
